//
//  TLMapViewController.m
//  Books
//
//  Created by tao故乡的云 on 2017/3/15.
//  Copyright © 2017年 故乡的云. All rights reserved.
//

#import "TLMapViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
@interface TLMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
@property(strong, nonatomic) BMKMapView *mapView;
@property(strong, nonatomic) BMKLocationService *locService;
@property(strong, nonatomic) BMKGeoCodeSearch *searcher;
@property(strong, nonatomic) UILabel *location;
@end


@implementation TLMapViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor yellowColor];
    
    // 添加地图
    CGRect frame = CGRectMake(5, 36, self.view.bounds.size.width - 10, self.view.bounds.size.height - 270);
    self.mapView = [[BMKMapView alloc] initWithFrame:frame];
    [self.view addSubview:self.mapView];
    
    // 定位
    [self setLocationService];
    // 反地理编码
    [self reverseGeoCode];
    
    
    // 添加地图选项组件View
    [self setupMapSwitch];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _searcher.delegate = self;

}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    [self startFollowHeading];
//    [self startLocation];
//}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _searcher.delegate = nil;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 地图选项设置
// 添加地图选项组件View
- (void)setupMapSwitch {
    // 设置地图类型
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"空白",@"标准",@"卫星"]];
    //    segment.numberOfSegments = 3;
    [segment addTarget:self action:@selector(setMapViewType:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:segment];
    //    segment.backgroundColor = [UIColor blueColor];
    segment.center = CGPointMake(self.view.center.x, self.view.bounds.size.height - 208);
    segment.bounds = CGRectMake(0, 0, 200, 30);
    segment.tintColor = [UIColor brownColor];
    segment.selectedSegmentIndex = 1;
    
    // 交通状况
    UISegmentedControl *segment2 = [[UISegmentedControl alloc] initWithItems:@[@"开启交通状况",@"关闭交通状况"]];
    [segment2 addTarget:self action:@selector(setTrafficEnabled:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:segment2];
    //    segment.backgroundColor = [UIColor blueColor];
    segment2.center = CGPointMake(self.view.center.x, self.view.bounds.size.height - 174);
    segment2.bounds = CGRectMake(0, 0, 200, 30);
    segment2.tintColor = [UIColor brownColor];
    segment2.selectedSegmentIndex = 1;
    
    // 热力地图
    UISegmentedControl *segment3 = [[UISegmentedControl alloc] initWithItems:@[@"开启热力地图",@"关闭热力地图"]];
    //    segment.numberOfSegments = 3;
    [segment3 addTarget:self action:@selector(setBaiduHeatMapEnabled:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:segment3];
    //    segment.backgroundColor = [UIColor blueColor];
    segment3.center = CGPointMake(self.view.center.x, self.view.bounds.size.height - 139);
    segment3.bounds = CGRectMake(0, 0, 200, 30);
    segment3.tintColor = [UIColor brownColor];
    segment3.selectedSegmentIndex = 1;
}

// 设置地图类型
- (void)setMapViewType:(UISegmentedControl *)segment {
    //    BMKMapTypeNone       = 0,               ///< 空白地图
    //    BMKMapTypeStandard   = 1,               ///< 标准地图
    //    BMKMapTypeSatellite  = 2,               ///< 卫星地图
    switch (segment.selectedSegmentIndex) {
        case 0:
            self.mapView.mapType = BMKMapTypeNone;
            break;
        case 1:
            self.mapView.mapType = BMKMapTypeStandard;
            break;
        case 2:
            self.mapView.mapType = BMKMapTypeSatellite;
            break;
        default:
            break;
    }
}

// 交通状况
- (void)setTrafficEnabled:(UISegmentedControl *)segment {
    
    switch (segment.selectedSegmentIndex) {
        case 0:
            //打开实时路况图层
            [_mapView setTrafficEnabled:YES];
            break;
        case 1:
            //关闭实时路况图层
            [_mapView setTrafficEnabled:NO];
            break;
        default:
            break;
    }
}

// 热力地图
- (void)setBaiduHeatMapEnabled:(UISegmentedControl *)segment {
    switch (segment.selectedSegmentIndex) {
        case 0:
            //打开百度城市热力图图层（百度自有数据）
            [_mapView setBaiduHeatMapEnabled:YES];
            break;
        case 1:
            //关闭百度城市热力图图层（百度自有数据）
            [_mapView setBaiduHeatMapEnabled:NO];
            break;
        default:
            break;
    }
}

#pragma mark - BMKMapViewDelegate
// Override
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}


#pragma mark - 定位
- (void)setLocationService {
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc] init];
    
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"普通",@"罗盘",@"跟随",@"罗盘2",@"停止"]];
    [segment addTarget:self action:@selector(setUserTrackingMode:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:segment];
    segment.center = CGPointMake(self.view.center.x, self.view.bounds.size.height - 105);
    segment.bounds = CGRectMake(0, 0, 200, 30);
    segment.tintColor = [UIColor brownColor];
   
    
    self.location = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    self.location.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.location];
     segment.selectedSegmentIndex = 1;
    [self setUserTrackingMode:segment];
}

- (void)setUserTrackingMode:(UISegmentedControl *)segment {
    switch (segment.selectedSegmentIndex) {
        case 0:
            [self startLocation];
            break;
        case 1:
            [self startFollowHeading];
            break;
        case 2:
            [self startFollowing];
            break;
        case 3:
            [self startHeading];
            break;
        case 4:
            [self stopLocation];
            break;
        default:
            break;
    }
    
}

//自定义精度圈
- (void)customLocationAccuracyCircle {
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    param.accuracyCircleStrokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5];
    param.accuracyCircleFillColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.3];
    [_mapView updateLocationViewWithParam:param];
}

//普通态------- 有问题，必须先启动其它模式后才能有效
-(void)startLocation {
    NSLog(@"进入普通定位态");
    [self stopLocation];
    //        _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    [_locService startUserLocationService];
    [_mapView setZoomLevel:14];//比例尺 级别，3-21
    
}
//罗盘态
-(void)startFollowHeading {
    NSLog(@"进入罗盘态");
    [self stopLocation];
    [_locService startUserLocationService];
    //    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
    _mapView.showsUserLocation = YES;
    [_mapView setZoomLevel:15];//比例尺 级别，3-21
}

//跟随态
-(void)startFollowing {
    NSLog(@"进入跟随态");
    [self stopLocation];
    [_locService startUserLocationService];
    //    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    [_mapView setZoomLevel:16];//比例尺 级别，3-21
}

//普通定位+定位罗盘模式
-(void)startHeading {
    NSLog(@"进入跟随态");
    [self stopLocation];
    [_locService startUserLocationService];
    //    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeHeading;
    _mapView.showsUserLocation = YES;
    [_mapView setZoomLevel:17];//比例尺 级别，3-21
}

//停止定位
-(void)stopLocation {
    [_locService stopUserLocationService];
    _mapView.showsUserLocation = NO;
    
}

#pragma mark - BMKLocationService Delegate
/**
 *在地图View将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.title);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    [_mapView updateLocationData:userLocation];
    [self getReverseGeoCode];
    NSLog(@"heading is %@",userLocation.title);
}

/**
 *在地图View停止定位后，会调用此函数
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

#pragma mark - 反地理编码
- (void)reverseGeoCode {
    //初始化检索对象
    _searcher =[[BMKGeoCodeSearch alloc] init];
}

//发起反向地理编码
- (void)getReverseGeoCode {
    CLLocation *point = _locService.userLocation.location; // 获取坐标
    CLLocationCoordinate2D pt = CLLocationCoordinate2DMake(point.coordinate.latitude, point.coordinate.longitude); // 坐标转换
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
    
}

#pragma mark - BMKGeoCodeSearchDelegate
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        _locService.userLocation.title = result.address;
        self.location.text = result.address;
    }else {
        NSLog(@"抱歉，未找到结果");
    }
}

- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

@end
